package com.crm.dao.base;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.crm.po.Users;

public class BaseHibernateDAO implements IBaseHibernateDAO {
	
	private static Logger logger = Logger.getLogger(BaseHibernateDAO.class);
	
	public Session getSession() {
		return HibernateSessionFactory.getSession();
	}
	
	public void closeSession() {
		HibernateSessionFactory.closeSession();
	}
	
	public String getUUID() {
		return UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
	}
	
	public List<?> findList(String hql) {		
		return findListPage(hql, 0, 0);
	}
	
	public List<?> findListPage(String hql, int start, int limit) {
		List<?> list = null;
		try {
			Query query = this.getSession().createQuery(hql);
			if(limit > 0){
				query.setFirstResult(start);
				query.setMaxResults(limit);
			}
			
			list = query.list();
		} catch (RuntimeException e) {
			logger.error(e);
		} finally {
			this.closeSession();	
		}
		return list;
	}
	
	public int executeHql(String hql) {
		int result = 0;
		Transaction transaction = getSession().beginTransaction();
		try {
			Query query = this.getSession().createQuery(hql);
			result = query.executeUpdate();
			transaction.commit();
		} catch (RuntimeException e) {
			transaction.rollback();
			logger.error(e);
		} finally {
			this.closeSession();	
		}
		return result;
	}
	
	public int getCount(String hql) {
		int count = 0;
		try {
			count = (Integer)this.getSession().createQuery(hql).uniqueResult();
		} catch (RuntimeException e) {
			logger.error(e);
		} finally {
			this.closeSession();	
		}
		return count;
	}
	
	public Object getUniqueResult(String hql) {
		Object obj = 0;
		try {
			obj = this.getSession().createQuery(hql).uniqueResult();
		} catch (RuntimeException e) {
			logger.error(e);
		} finally {
			this.closeSession();	
		}
		return obj;
	}
	
	
	public Map<String, String> getMap(Class clazz, String keyName, String valueName) {
		Map<String, String> map = null;
		
		try {
			String hql = "select T." + keyName + ", T." + valueName + " from " + clazz.getName() + " T ";
			System.out.println(hql);
			List list = this.getSession().createQuery(hql).list();			
			if(list != null && list.size() > 0){
				map = new HashMap<String, String>();
				for(int i = 0; i < list.size(); i ++){
					Object[] array = (Object[]) list.get(i);
					if(array[0] == null || array[1] == null){
						continue;
					}
					map.put((String) array[0], (String) array[1]);
				}
			}
		} catch (RuntimeException e) {
			logger.error(e);
		} finally {
			this.closeSession();	
		}
		return map;
	}
	
	public static void main(String[] s){
		BaseHibernateDAO b = new BaseHibernateDAO();
		Map map = b.getMap(Users.class, "uid", "nickname");
	}
	
}